using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using CDIO1.Models;
using System.Data;
using Microsoft.Office.Interop.Word;
using System.Reflection;

namespace CDIO1.Controllers
{
    public class AdminController : Controller
    {
        //
        // GET: /Admin/

        public ActionResult Index()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                if (!User.IsInRole("admin"))
                {
                    return RedirectToAction("Index", "Home");
                }
            }            
            return View();
        }

        public ActionResult ManageAccount()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                if (!User.IsInRole("admin"))
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            return View();
        }

        public ActionResult ManageUserType()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                if (!User.IsInRole("admin"))
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            return View();
        }

        public ActionResult ManageLanguage()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                if (!User.IsInRole("admin"))
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            return View();
        }

        public ActionResult ManageMethod()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                if (!User.IsInRole("admin"))
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            return View();
        }

        public ActionResult ManageTeachMethodLanguage()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                if (!User.IsInRole("admin"))
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            return View();
        }

        public ActionResult ManageEvalMethodLanguage()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                if (!User.IsInRole("admin"))
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            return View();
        }

        public ActionResult ManageProgram()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                if (!User.IsInRole("admin"))
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            return View();
        }

        public ActionResult ManageMajor()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                if (!User.IsInRole("admin"))
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            return View();
        }

        public ActionResult ManageStandard()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                if (!User.IsInRole("admin"))
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            return View();
        }

        public ActionResult ManageStaff()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                if (!User.IsInRole("admin"))
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            return View();
        }

        public ActionResult ManageBloom()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                if (!User.IsInRole("admin"))
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            return View();
        }

        public ActionResult VerbList()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                if (!User.IsInRole("admin"))
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            return View();
        }

        public ActionResult ManageCourse()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                if (!User.IsInRole("admin"))
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            return View();
        }
        public ActionResult ManageSyllabus(string id)
        {
            if (!User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                if (!User.IsInRole("admin"))
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            int _id = 0;
            bool check = Int32.TryParse(id, out _id);
            ViewData["scheduleID"] = "-1";
            if (!check) // parameter id is invalid
            {

            }
            else
            {
                ViewData["courseID"] = _id;
                var db = new SyllabusDataContext();
                var syll = from p in db.Syllabus where p.CourseID == _id select p;
                if (syll.Count() > 0)
                {
                    foreach (Syllabus s in syll)
                    {
                        ViewData["scheduleID"] = s.TeachingScheduleID;
                        ViewData["syllabusID"] = s.ID;
                    }
                }
            }
            return View();
        }

        public ActionResult ManageProgramDetail()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                if (!User.IsInRole("admin"))
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            return View(); 

        }


        public ActionResult ManageCourseOfMajor()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                if (!User.IsInRole("admin"))
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            return View();
        }

        public ActionResult UpdateContentName(string id, string content)
        {
            if (!User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                if (!User.IsInRole("admin"))
                {
                    return RedirectToAction("Index", "Home");
                }
            }

            int contentID = Int32.Parse(id);
            if (content.CompareTo("") != 0)
            {
                var db = new SyllabusDataContext();
                CourseContent c = db.CourseContents.Single(p => p.ID == contentID);
                c.ChapterName = content;
                db.SubmitChanges();
                return Content("1");
            }
            else {
                return Content("0");
            }            
        }

        public ActionResult UpdateContentLO(string id, string content)
        {
            if (!User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                if (!User.IsInRole("admin"))
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            int contentID = Int32.Parse(id);
            if (content.CompareTo("") != 0)
            {
                var db = new SyllabusDataContext();
                CourseContent c = db.CourseContents.Single(p => p.ID == contentID);
                c.CourseLOID = content;
                db.SubmitChanges();
                return Content("1");
            }
            else
            {
                return Content("0");
            }
        }

        public ActionResult DeleteCourseContent(string id)
        {
            if (!User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                if (!User.IsInRole("admin"))
                {
                    return RedirectToAction("Index", "Home");
                }
            }

            int contentID = Int32.Parse(id);
            RecursiveDeleteNode(contentID);
            return Content("");
        }

        public void RecursiveDeleteNode(int id)
        {
            var db = new SyllabusDataContext();
            List<CourseContent> lst = (from p in db.CourseContents
                     where p.ParentID == id && p.ID != p.ParentID
                     select p).ToList();
            if (lst.Count == 0)
            {
                CourseContent c = db.CourseContents.Single(m => m.ID == id);
                c.Status = 0;
                db.SubmitChanges();
            }
            else {
                for (int i = 0; i < lst.Count; i++)
                {
                    RecursiveDeleteNode(lst[i].ID);
                }
                CourseContent c = db.CourseContents.Single(m => m.ID == id);
                c.Status = 0;
                db.SubmitChanges();
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UpdateCourseSkill(string ContentID, bool option1, string iSkill, bool option2, string gSkill)
        {
            var db = new SyllabusDataContext();
            int id = Int32.Parse(ContentID);

            CourseContent c = db.CourseContents.Single(p => p.ID == id);
            c.IsIndividualSkill = option1;
            if (option1) {
                c.IndividualSkill = iSkill;
            }
            else {
                c.IndividualSkill = "";
            }

            c.IsGroupSkill = option2;
            if (option2) {
                c.GroupSkill = gSkill;
            }
            else {
                c.GroupSkill = "";
            }

            db.SubmitChanges();
            return Content("");
        }

        public ActionResult ManageStandardLO()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                if (!User.IsInRole("admin"))
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            return View();
        }

        public ActionResult ViewStaffInformation()
        {
            if (!User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }
            else
            {
                if (!User.IsInRole("admin"))
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            return View();
        }

        public ActionResult PrintSyllabus(string id)
        {
            string appPath = System.Web.HttpContext.Current.Request.ApplicationPath;
            string physicalPath = System.Web.HttpContext.Current.Request.MapPath(appPath);

            // start word and get Application object
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document doc = null;
            //word.Visible = true;

            object filename = physicalPath + "\\step1.doc";
            object nullobj = Missing.Value;
            doc = word.Documents.Open(ref filename, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj);

            // using to add checkbox
            Microsoft.Office.Interop.Word.WdFieldType Type = Microsoft.Office.Interop.Word.WdFieldType.wdFieldFormCheckBox;
            Microsoft.Office.Interop.Word.Range oRange;
            Microsoft.Office.Interop.Word.FormField oFormfield;
            Microsoft.Office.Interop.Word.WdRulerStyle RulerStyle = Microsoft.Office.Interop.Word.WdRulerStyle.wdAdjustNone;

            Microsoft.Office.Interop.Word.Tables lstTable = doc.Tables;

            int _id;
            int syllabusID = Convert.ToInt32(id);
            _id = syllabusID;
            var db = new SyllabusDataContext();
            var syll1 = from p in db.Syllabus where p.CourseID == _id select p;
            if (syll1.Count() > 0)
            {
                foreach (Syllabus s in syll1)
                {                    
                    syllabusID = s.ID;
                }
            }

            var sDB = new SyllabusDataContext();
            object numRow = 1;
            object numCol = 2;
            object beforeRow;
            Microsoft.Office.Interop.Word.Row row;

            object oFont = "Wingdings";
            object oCollapseStart = Microsoft.Office.Interop.Word.WdCollapseDirection.wdCollapseStart;
            // print course content
            #region print course content

            Microsoft.Office.Interop.Word.Table tContent = lstTable[8]; //get course content table in doc

            float w1 = tContent.Rows[1].Cells[1].Width;// tContent.Columns[1].Width;
            float w2 = tContent.Rows[1].Cells[2].Width;// tContent.Columns[2].Width;

            int index = 0;
            int pos = 0;
            int chapt = 0;

            List<GetCourseContentResult> contentLst = sDB.GetCourseContent(syllabusID).ToList();
            GetCourseContentResult content;

            for (int i = 0; i < contentLst.Count; i++)
            {
                content = contentLst[i];
                switch (content.NodeLevel)
                {
                    case 0:
                        if (chapt != 0)
                        {
                            beforeRow = tContent.Rows[tContent.Rows.Count - 3];
                            row = tContent.Rows.Add(ref beforeRow);
                            row.Cells[1].SetWidth(140f, RulerStyle);
                            row.Cells[2].SetWidth(w1 + w2 - 140f, RulerStyle);
                            oRange = row.Cells[1].Range;
                            oRange.Collapse(ref oCollapseStart);
                            //oFormfield = doc.FormFields.Add(oRange, Type);
                            if ((bool)contentLst[pos].IsIndividualSkill)
                            {
                                //oFormfield.CheckBox.Value = true;
                                oRange.InsertSymbol(120, ref oFont, ref nullobj, ref nullobj);
                            }
                            else
                            {
                                oRange.InsertSymbol(168, ref oFont, ref nullobj, ref nullobj);
                                //oFormfield.CheckBox.Value = false;
                            }
                            row.Cells[1].Range.InsertAfter(" Ky nang ca nhan");
                            row.Cells[1].Range.Bold = 0;
                            row.Cells[2].Range.Paragraphs.Alignment =
                                                Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                            row.Cells[2].Range.Text = "" + contentLst[pos].IndividualSkill;

                            // GroupSkill

                            beforeRow = tContent.Rows[tContent.Rows.Count - 3];
                            row = tContent.Rows.Add(ref beforeRow);
                            row.Cells[1].SetWidth(140f, RulerStyle);
                            row.Cells[2].SetWidth(w1 + w2 - 140f, RulerStyle);
                            oRange = row.Cells[1].Range;
                            oRange.Collapse(ref oCollapseStart);
                            //oFormfield = doc.FormFields.Add(oRange, Type);
                            if ((bool)contentLst[pos].IsGroupSkill)
                            {
                                //oFormfield.CheckBox.Value = true;
                                oRange.InsertSymbol(120, ref oFont, ref nullobj, ref nullobj);
                            }
                            else
                            {
                                //oFormfield.CheckBox.Value = false;
                                oRange.InsertSymbol(168, ref oFont, ref nullobj, ref nullobj);
                            }
                            row.Cells[1].Range.InsertAfter(" Ky nang nhom");
                            row.Cells[1].Range.Bold = 0;
                            row.Cells[2].Range.Paragraphs.Alignment =
                                                Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                            row.Cells[2].Range.Text = "" + contentLst[pos].GroupSkill;

                            if (index != 0)
                            {
                                tContent.Rows[index].Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineStyle =
                                                    Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                            }
                            index = tContent.Rows.Count - 4;
                        }
                        chapt = 1;
                        pos = i;

                        beforeRow = tContent.Rows[tContent.Rows.Count - 3];
                        row = tContent.Rows.Add(ref beforeRow);
                        row.Cells[1].SetWidth(w1, RulerStyle);
                        row.Cells[2].SetWidth(w2, RulerStyle);
                        row.Cells[1].Range.Text = "Chapter " + content.OrderNode + "." + content.ChapterName;
                        row.Cells[1].Range.Bold = 1;
                        row.Cells[2].Range.Paragraphs.Alignment =
                                                Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                        row.Cells[2].Range.Text = "" + content.CourseLOID;

                        break;
                    case 1:
                        beforeRow = tContent.Rows[tContent.Rows.Count - 3];
                        row = tContent.Rows.Add(ref beforeRow);
                        row.Cells[1].SetWidth(w1, RulerStyle);
                        row.Cells[2].SetWidth(w2, RulerStyle);
                        row.Cells[1].Range.Text = "\t" + content.OrderNode + "." + content.ChapterName;
                        row.Cells[1].Range.Bold = 0;
                        row.Cells[2].Range.Paragraphs.Alignment =
                                                Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                        row.Cells[2].Range.Text = "" + content.CourseLOID;

                        break;
                    case 2:
                        beforeRow = tContent.Rows[tContent.Rows.Count - 3];
                        row = tContent.Rows.Add(ref beforeRow);
                        row.Cells[1].SetWidth(w1, RulerStyle);
                        row.Cells[2].SetWidth(w2, RulerStyle);
                        row.Cells[1].Range.Text = "\t\t" + content.OrderNode + "." + content.ChapterName;
                        row.Cells[1].Range.Bold = 0;
                        row.Cells[2].Range.Paragraphs.Alignment =
                                                Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                        row.Cells[2].Range.Text = "" + content.CourseLOID;

                        break;
                }
            }

            if (contentLst.Count > 0)
            {
                beforeRow = tContent.Rows[tContent.Rows.Count - 3];
                row = tContent.Rows.Add(ref beforeRow);
                row.Cells[1].SetWidth(140f, RulerStyle);
                row.Cells[2].SetWidth(w1 + w2 - 140f, RulerStyle);
                oRange = row.Cells[1].Range;
                oRange.Collapse(ref oCollapseStart);
                //oFormfield = doc.FormFields.Add(oRange, Type);
                if ((bool)contentLst[pos].IsIndividualSkill)
                {
                    oRange.InsertSymbol(120, ref oFont, ref nullobj, ref nullobj);
                    //oFormfield.CheckBox.Value = true;
                }
                else
                {
                    //oFormfield.CheckBox.Value = false;
                    oRange.InsertSymbol(168, ref oFont, ref nullobj, ref nullobj);
                }
                row.Cells[1].Range.InsertAfter(" Ky nang ca nhan");
                row.Cells[1].Range.Bold = 0;
                row.Cells[2].Range.Paragraphs.Alignment =
                                                Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                row.Cells[2].Range.Text = "" + contentLst[pos].IndividualSkill;

                // GroupSkill
                beforeRow = tContent.Rows[tContent.Rows.Count - 3];
                row = tContent.Rows.Add(ref beforeRow);
                row.Cells[1].SetWidth(140f, RulerStyle);
                row.Cells[2].SetWidth(w1 + w2 - 140f, RulerStyle);
                oRange = row.Cells[1].Range;
                oRange.Collapse(ref oCollapseStart);
                //oFormfield = doc.FormFields.Add(oRange, Type);
                if ((bool)contentLst[pos].IsGroupSkill)
                {
                    //oFormfield.CheckBox.Value = true;
                    oRange.InsertSymbol(120, ref oFont, ref nullobj, ref nullobj);
                }
                else
                {
                    //oFormfield.CheckBox.Value = false;
                    oRange.InsertSymbol(168, ref oFont, ref nullobj, ref nullobj);
                }
                row.Cells[1].Range.InsertAfter(" Ky nang nhom");
                row.Cells[1].Range.Bold = 0;
                row.Cells[2].Range.Paragraphs.Alignment =
                                                Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                row.Cells[2].Range.Text = "" + contentLst[pos].GroupSkill;

                if (index != 0)
                {
                    tContent.Rows[index].Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineStyle =
                                        Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                }
                //index = tContent.Rows.Count-3;
                //tContent.Rows[index].Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineStyle =
                //                        Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
            }
            row = tContent.Rows[tContent.Rows.Count - 3];
            row.Delete();

            tContent.Rows[1].Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineStyle =
                                        Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;

            List<CourseSkill> lstCourseSkill = (from p in sDB.CourseSkills
                                                where p.SyllabusID == syllabusID && p.Status == 1
                                                select p).ToList();
            if (lstCourseSkill.Count > 0)
            {
                row = tContent.Rows[tContent.Rows.Count - 1];
                oRange = row.Cells[1].Range;
                oRange.Collapse(ref oCollapseStart);
                //oFormfield = doc.FormFields.Add(oRange, Type);
                row.Cells[1].Range.InsertAfter(" Ky nang ca nhan");
                if ((bool)lstCourseSkill[0].IsIndividualSkill)
                {
                    //oFormfield.CheckBox.Value = true;
                    oRange.InsertSymbol(120, ref oFont, ref nullobj, ref nullobj);
                    row.Cells[2].Range.Text = lstCourseSkill[0].IndividualSkill + "";
                }

                row = tContent.Rows[tContent.Rows.Count];
                oRange = row.Cells[1].Range;
                oRange.Collapse(ref oCollapseStart);
                //oFormfield = doc.FormFields.Add(oRange, Type);
                row.Cells[1].Range.InsertAfter(" Ky nang nhom");
                if ((bool)lstCourseSkill[0].IsGroupSkill)
                {
                    //oFormfield.CheckBox.Value = true;
                    oRange.InsertSymbol(120, ref oFont, ref nullobj, ref nullobj);
                    row.Cells[2].Range.Text = lstCourseSkill[0].GroupSkill + "";
                }
            }

    #endregion


            #region print teaching method table

            // print teaching method table
            Microsoft.Office.Interop.Word.Table tTeachingMethod = lstTable[9]; 
            List<TeachMethodSyllabus> lstTMethodSyllabus = (from p in sDB.TeachMethodSyllabus
                                     where p.SyllabusID == syllabusID && p.Status == 1
                                     select p).ToList();    
           
            var methodDB = new MethodDataContext();
            var lstAllTMethod = from m in methodDB.TeachingMethods
                                join m1 in methodDB.TeachingMethodLanguages
                                on m.ID equals m1.TeachingMethodID
                                where m1.LanguageID == 1
                                select new
                                {
                                    ID = m.ID,
                                    MethodID = m.MethodID,
                                    MethodName = m1.Method
                                };

            int nCheckbox = doc.FormFields.Count;
            int posTeachMethod = -1;
            foreach (var t in lstAllTMethod)
            {
                row = tTeachingMethod.Rows.Add(ref nullobj);
                row.Cells[1].Range.Text = t.MethodID.Trim() + ".";
                row.Cells[2].Range.Text = t.MethodName.Trim() + "";

                oRange = row.Cells[3].Range;
                oRange.Collapse(ref oCollapseStart);
                //oFormfield = doc.FormFields.Add(oRange, Type);
                nCheckbox++;
                posTeachMethod = this.FindTeachMethodS(lstTMethodSyllabus, t.ID);
                if (posTeachMethod != -1)
                {
                    //object oCheckbox = nCheckbox;
                    //oFormfield = doc.FormFields.get_Item(ref oCheckbox);
                    //oFormfield.CheckBox.Value = true;
                    oRange.InsertSymbol(120, ref oFont, ref nullobj, ref nullobj);
                    row.Cells[4].Range.Text = lstTMethodSyllabus[posTeachMethod].Description + "";
                }
                else {
                    oRange.InsertSymbol(168, ref oFont, ref nullobj, ref nullobj);
                }                
            }
            row = tTeachingMethod.Rows[2];
            row.Delete();

    #endregion


            #region print evaluate method table

            //print evaluate method table
            Microsoft.Office.Interop.Word.Table tEvaluateMethod = lstTable[10];
            List<EvalMethodSyllabus> lstEMethodSyllabus = (from p in sDB.EvalMethodSyllabus
                                                            where p.SyllabusID == syllabusID && p.Status == 1
                                                            select p).ToList();

            var lstAllEMethod = from m in methodDB.EvaluateMethods
                                join m1 in methodDB.EvaluateMethodLanguages
                                on m.ID equals m1.EvaluateID
                                where m1.LanguageID == 1
                                select new
                                {
                                    ID = m.ID,
                                    MethodID = m.MethodID,
                                    MethodName = m1.Method
                                };
            nCheckbox = doc.FormFields.Count;
            int posEvalMethod = -1;
            foreach (var t in lstAllEMethod)
            {
                beforeRow = tEvaluateMethod.Rows[tEvaluateMethod.Rows.Count-1];
                row = tEvaluateMethod.Rows.Add(ref beforeRow);
                row.Cells[1].Range.Text = t.MethodID.Trim() + ".";
                row.Cells[2].Range.Text = t.MethodName.Trim() + "";

                oRange = row.Cells[3].Range;
                oRange.Collapse(ref oCollapseStart);
                //oFormfield = doc.FormFields.Add(oRange, Type);
                nCheckbox++;
                posEvalMethod = this.FindEvalMethodS(lstEMethodSyllabus, t.ID);
                if (posEvalMethod != -1)
                {
                    //object oCheckbox = nCheckbox;
                    //oFormfield = doc.FormFields.get_Item(ref oCheckbox);
                    //oFormfield.CheckBox.Value = true;
                    oRange.InsertSymbol(120, ref oFont, ref nullobj, ref nullobj);
                    row.Cells[4].Range.Text = lstEMethodSyllabus[posEvalMethod].Percentage + " %";
                    row.Cells[5].Range.Text = lstEMethodSyllabus[posEvalMethod].CorrespondLOs;
                }
                else
                {
                    oRange.InsertSymbol(168, ref oFont, ref nullobj, ref nullobj);
                }
            }
            row = tEvaluateMethod.Rows[tEvaluateMethod.Rows.Count - 1];
            row.Delete();

            List<GradeFormula> gradeFormula = (from p in sDB.GradeFormulas
                                where p.SyllabusID == syllabusID && p.Status == 1
                                select p).ToList();
            if (gradeFormula.Count > 0)
            {
                row = tEvaluateMethod.Rows[tEvaluateMethod.Rows.Count];
                row.Cells[2].Range.Text = gradeFormula[0].Formula + "";
            }

    #endregion


            #region print theory lecture table

            int courseScheID = 0;            
            var syll = from p in sDB.Syllabus where p.ID == syllabusID select p;
            if (syll.Count() > 0)
            {
                foreach (Syllabus s in syll)
                {
                    courseScheID = (int)s.TeachingScheduleID;
                }
            }

            //print theory lecture table
            Microsoft.Office.Interop.Word.Table tTheoryLecture = lstTable[11];
            var scheDB = new CourseScheduleDataContext();
            var lstTheoryL = from p in scheDB.TheoryLectures
                             join p1 in scheDB.TeachMethodSyllabus1s on p.TeachingMethodID equals p1.ID
                             join p2 in scheDB.TeachingMethod1s on p1.TeachingMethodID equals p2.ID
                             join e in scheDB.EvalMethodSyllabus1s on p.EvalMethodID equals e.ID
                             join e1 in scheDB.EvaluateMethod1s on e.EvalMethodID equals e1.ID
                             where p.CourseScheduleID == courseScheID && p.Status == 1
                             select new
                             {
                                 Title = p.Title,
                                 Topic = p.Topic,
                                 Chapter = p.Chapter,
                                 Reference = p.Reference,
                                 TopicDescription = p.TopicDescription,
                                 ReferenceData = p.ReferenceData,
                                 TeachingMethodCode = p2.MethodID,
                                 EvalMethodCode = e1.MethodID,
                                 Duration = p.Duration
                             };
            beforeRow = tTheoryLecture.Rows[tTheoryLecture.Rows.Count];
            int count = 0;            
            foreach (var t in lstTheoryL)
            {
                count++;
                tTheoryLecture.Rows.Add(ref beforeRow);

                row = tTheoryLecture.Rows.Add(ref beforeRow);
                row.Cells[2].Merge(row.Cells[3]);
                row.Cells[2].Merge(row.Cells[3]);
                row.Cells[2].Merge(row.Cells[3]);

                row = tTheoryLecture.Rows.Add(ref beforeRow);
                row.Cells[2].Merge(row.Cells[3]);
                row.Cells[2].Merge(row.Cells[3]);
                row.Cells[2].Merge(row.Cells[3]);                
                

                tTheoryLecture.Cell(tTheoryLecture.Rows.Count - 3, 1).Range.Text = count + ". " + t.Title.Trim();                

                oRange = tTheoryLecture.Cell(tTheoryLecture.Rows.Count - 1, 1).Range;
                oRange.Collapse(ref oCollapseStart);
                tTheoryLecture.Cell(tTheoryLecture.Rows.Count - 1, 1).Range.Bold = 1;
                //oFormfield = doc.FormFields.Add(oRange, Type);
                if ((bool)t.Reference)
                {
                    //oFormfield.CheckBox.Value = true;
                    oRange.InsertSymbol(120, ref oFont, ref nullobj, ref nullobj);
                }
                else
                {
                    oRange.InsertSymbol(168, ref oFont, ref nullobj, ref nullobj);
                }
                oRange.InsertBefore("Tai lieu doc them ");

                oRange = tTheoryLecture.Cell(tTheoryLecture.Rows.Count - 2, 1).Range;
                oRange.Collapse(ref oCollapseStart);
                tTheoryLecture.Cell(tTheoryLecture.Rows.Count - 2, 1).Range.Bold = 1;
                //oFormfield = doc.FormFields.Add(oRange, Type);
                if ((bool)t.Topic)
                {
                    oRange.InsertSymbol(120, ref oFont, ref nullobj, ref nullobj);
                    //oFormfield.CheckBox.Value = true;
                }
                else
                {
                    oRange.InsertSymbol(168, ref oFont, ref nullobj, ref nullobj);
                }
                oRange.InsertBefore("Tom tat chu de bai tap ");
                tTheoryLecture.Cell(tTheoryLecture.Rows.Count - 2, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineStyle
                                        = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleNone;
                tTheoryLecture.Cell(tTheoryLecture.Rows.Count - 2, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].LineStyle
                                        = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleNone;                

                tTheoryLecture.Cell(tTheoryLecture.Rows.Count - 3, 2).Range.Text = t.Chapter.Trim() + "";
                tTheoryLecture.Cell(tTheoryLecture.Rows.Count - 3, 3).Range.Text = t.TeachingMethodCode.Trim() + "";
                tTheoryLecture.Cell(tTheoryLecture.Rows.Count - 3, 4).Range.Text = t.EvalMethodCode.Trim() + "";
                tTheoryLecture.Cell(tTheoryLecture.Rows.Count - 3, 5).Range.Text = t.Duration.Trim() + "";
                tTheoryLecture.Cell(tTheoryLecture.Rows.Count - 2, 2).Range.Text = t.TopicDescription.Trim() + "";
                tTheoryLecture.Cell(tTheoryLecture.Rows.Count - 1, 2).Range.Text = t.ReferenceData.Trim() + "";
            }
            count = tTheoryLecture.Rows.Count;
            tTheoryLecture.Cell(count, 1).Merge(tTheoryLecture.Cell(count, 2));
            tTheoryLecture.Cell(count, 1).Merge(tTheoryLecture.Cell(count, 2));
            tTheoryLecture.Cell(count, 1).Merge(tTheoryLecture.Cell(count, 2));
            tTheoryLecture.Cell(count, 1).Merge(tTheoryLecture.Cell(count, 2));
            tTheoryLecture.Cell(count, 1).Delete(ref nullobj);

            #endregion


            #region print practiceLecture table

            count = 0;
            Microsoft.Office.Interop.Word.Table tPractice = lstTable[12];
            var lstPractice = from p in scheDB.Practices
                                         where p.CourseScheduleID == courseScheID && p.Status == 1
                                         select p;
            foreach (Practice pr in lstPractice)
            {
                count++;
                row = tPractice.Rows.Add(ref nullobj);

                oRange = row.Cells[1].Range;                
               
                oRange.Text = " Lam o nha";
                oFormfield = doc.FormFields.Add(oRange, Type);
                if ((bool)pr.HomePractice)
                {
                    oFormfield.CheckBox.Value = true;                    
                }

                oRange.InsertBefore(" Lam tai phong Lab\n");
                oFormfield = doc.FormFields.Add(oRange, Type);
                if ((bool)pr.LabPractice)
                {
                    oFormfield.CheckBox.Value = true;                    
                }

                oRange.InsertBefore(" Co giang bai tren Lab\n");
                oFormfield = doc.FormFields.Add(oRange, Type);
                if ((bool)pr.LectureLab)
                {
                    oFormfield.CheckBox.Value = true;                    
                }                

                oRange.InsertBefore(count + ". " + pr.Name + "\n");
                row.Cells[2].Range.Text = pr.Chapter.Trim();                
                row.Cells[3].Range.Text = pr.WorkingHour + "";                
                row.Cells[4].Range.Text = pr.Resources.Trim();                
                row.Cells[5].Range.Text = pr.Duration.Trim();                
            }

            row = tPractice.Rows[2];
            row.Delete();

            #endregion


            #region print courseProject table

            count = 0;
            Microsoft.Office.Interop.Word.Table tProject = lstTable[13];

            var lstProject = from p in scheDB.Projects
                              where p.CourseScheduleID == courseScheID && p.Status == 1
                              select p;
            foreach (Project pr in lstProject)
            {
                count++;
                row = tProject.Rows.Add(ref nullobj);

                oRange = row.Cells[1].Range;
                oRange.Text = " Co di thuc te";
                oFormfield = doc.FormFields.Add(oRange, Type);
                if ((bool)pr.RealProject)
                {
                    oFormfield.CheckBox.Value = true;
                }

                oRange.InsertBefore(" Co thuyet trinh tren lop\n");
                oFormfield = doc.FormFields.Add(oRange, Type);
                if ((bool)pr.Presentation)
                {
                    oFormfield.CheckBox.Value = true;
                }

                oRange.InsertBefore(count + ". " + pr.Name + "\n");
                row.Cells[2].Range.Text = pr.Chapter.Trim();                
                row.Cells[3].Range.Text = pr.WorkingHour + "";                
                row.Cells[4].Range.Text = pr.Resources.Trim();                
                row.Cells[5].Range.Text = pr.Duration.Trim();               
            }

            row = tProject.Rows[2];
            row.Delete();

            #endregion


            #region print summary courseSchedule

            Microsoft.Office.Interop.Word.Table tSummary = lstTable[14];
            beforeRow = tSummary.Rows[tSummary.Rows.Count];
            numRow = 1;
            numCol = 15;

            row = tSummary.Rows.Add(ref beforeRow);
            row.Cells[1].Range.Bold = 1;
            row.Cells[1].Range.Text = "Bai giang ly thuyet";

            var lecture = scheDB.GetLectureInfo(courseScheID);
            foreach (GetLectureInfoResult lec in lecture)
            {
                row = tSummary.Rows.Add(ref beforeRow);
                row.Cells[1].Range.Text = lec.Title;
                row.Cells[2].Split(ref numRow, ref numCol);

                string duration = lec.Duration.Trim();
                string[] weeks = duration.Split('-');
                int a1, a2;
                a1 = Convert.ToInt32(weeks[0]);
                if (weeks.Length == 2) {
                  a2 = Convert.ToInt32(weeks[1]);
                }
                else {
                  a2 = a1;
                }
                for (int i = 1; i < 16; i++)
                {
                    if (a1 <= i && i <= a2) {
                        row.Cells[i + 1].Range.Shading.BackgroundPatternColor
                                    = Microsoft.Office.Interop.Word.WdColor.wdColorGray25;
                    }
                }
            }


            row = tSummary.Rows.Add(ref beforeRow);
            row.Cells[1].Range.Bold = 1;
            row.Cells[1].Range.Text = "Bai giang thuc tap va thuc hanh";

            var practice = scheDB.GetPracticeInfo(courseScheID);
            foreach (GetPracticeInfoResult prac in practice)
            {
                row = tSummary.Rows.Add(ref beforeRow);
                row.Cells[1].Range.Text = prac.Name;
                row.Cells[2].Split(ref numRow, ref numCol);

                string duration = prac.Duration.Trim();
                string[] weeks = duration.Split('-');
                int a1, a2;
                a1 = Convert.ToInt32(weeks[0]);
                if (weeks.Length == 2)
                {
                    a2 = Convert.ToInt32(weeks[1]);
                }
                else
                {
                    a2 = a1;
                }
                for (int i = 1; i < 16; i++)
                {
                    if (a1 <= i && i <= a2)
                    {
                        row.Cells[i + 1].Range.Shading.BackgroundPatternColor
                                    = Microsoft.Office.Interop.Word.WdColor.wdColorGray25;
                    }
                }
            }

            row = tSummary.Rows.Add(ref beforeRow);
            row.Cells[1].Range.Bold = 1;
            row.Cells[1].Range.Text = "Do an";

            var project = scheDB.GetProjectInfo(courseScheID);
            foreach (GetProjectInfoResult proj in project)
            {
                row = tSummary.Rows.Add(ref beforeRow);
                row.Cells[1].Range.Text = proj.Name;
                row.Cells[2].Split(ref numRow, ref numCol);

                string duration = proj.Duration.Trim();
                string[] weeks = duration.Split('-');
                int a1, a2;
                a1 = Convert.ToInt32(weeks[0]);
                if (weeks.Length == 2)
                {
                    a2 = Convert.ToInt32(weeks[1]);
                }
                else
                {
                    a2 = a1;
                }
                for (int i = 1; i < 16; i++)
                {
                    if (a1 <= i && i <= a2)
                    {
                        row.Cells[i + 1].Range.Shading.BackgroundPatternColor
                                    = Microsoft.Office.Interop.Word.WdColor.wdColorGray25;
                    }
                }
            }


            row = tSummary.Rows[tSummary.Rows.Count];
            row.Delete();

            #endregion


            filename = physicalPath + "\\output.doc";
            word.ActiveDocument.SaveAs(ref filename, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj);

            doc.Close(ref nullobj, ref nullobj, ref nullobj);
            word.Quit(ref nullobj, ref nullobj, ref nullobj);
            return Content("1");
        }

        int FindEvalMethodS(List<EvalMethodSyllabus> lst, int id)
        {
            for (int i = 0; i < lst.Count; i++)
            {
                if (lst[i].EvalMethodID == id)
                {
                    return i;
                }
            }
            return -1;
        }

        int FindTeachMethodS(List<TeachMethodSyllabus> lst, int id)
        {
            for (int i = 0; i < lst.Count; i++)
            {
                if (lst[i].TeachingMethodID == id)
                {
                    return i;
                }
            }
            return -1;
        }
    }     
}
